﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZYB.Security
{
    /// <summary>
    /// 
    /// </summary>
    internal static class Base64Tools
    {
        private static readonly char[] Base64Code = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
        private static sbyte[] Base64Decode = new sbyte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 63, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 };
        public static string Encode(byte[] b)
        {
            var code = 0;
            if (b == null)
                throw new ArgumentNullException(nameof(b));
            var sb=new StringBuilder((b.Length-1)/3<<6);
            for (var i = 0; i < b.Length; ++i)
            {
                code |= b[i] << 16 - i % 3 * 8 & 255 << 16 - i % 3 * 8;
                if (i % 3 != 2 && i != b.Length - 1) continue;
                sb.Append(Base64Code[RightMove(code & 16515072,18)]);
                sb.Append(Base64Code[RightMove(code & 258048,12)]);
                sb.Append(Base64Code[RightMove(code & 4032,6)]);
                sb.Append(Base64Code[code & 63]);
                code = 0;
            }
            if (b.Length % 3 > 0)
                sb[sb.Length - 1] = '=';
            if (b.Length % 3 == 1)
                sb[sb.Length - 2] = '=';
            return sb.ToString();

        }

        public static byte[] Decode(string code)
        {
            if(code==null)
                throw new ArgumentNullException(nameof(code));
            var len = code.Length;
            if(len%4!=0)
                throw new ArgumentOutOfRangeException(nameof(code));
            if(len==0)
                return new byte[0];
            int pad = 0;
            if (code[len - 1] == 61)
                ++pad;
            if (code[len - 2] == 61)
                ++pad;
            var retLen = len / 4 * 3 - pad;
            var ret = new byte[retLen];
            for (var i = 0; i < len;i+=4)
            {
                var j = i / 4 * 3;
                var ch1 = code[i];
                var ch2 = code[i + 1];
                var ch3 = code[i + 2];
                var ch4 = code[i + 3];
                var tmp = Base64Decode[ch1] << 18 | Base64Decode[ch2] << 12 | Base64Decode[ch3] << 6 | Base64Decode[ch4];

                ret[j]= (byte)((tmp & 16711680) >> 16);
                if (i < len - 4)
                {
                    ret[j + 1] = (byte)((tmp & '\uff00') >> 8);
                    ret[j + 2] = (byte)(tmp & 255);
                }
                else
                {
                    if (j + 1 < retLen)
                    {
                        ret[j + 1] = (byte)((tmp & '\uff00') >> 8);
                    }

                    if (j + 2 < retLen)
                    {
                        ret[j + 2] = (byte)(tmp & 255);
                    }
                }
            }
            return ret;
        }

        private static int RightMove(int value, int pos)
        {
            if (pos == 0) return value;
            const int mask = 0x7fffffff; // int.MaxValue = 0x7FFFFFFF 整数最大值
            value >>= 1;               //无符号整数最高位不表示正负但操作数还是有符号的，有符号数右移1位，正数时高位补0，负数时高位补1
            value &= mask;     //和整数最大值进行逻辑与运算，运算后的结果为忽略表示正负值的最高位
            value >>= pos - 1;     //逻辑运算后的值无符号，对无符号的值直接做右移运算，计算剩下的位
            return value;
        }
    }
}
